from selenium import webdriver
from base.json_read import get_json_element
from config import PROJECT_ROOT
import os
from selenium.webdriver.common.by import By

class PageBase:
    def __init__(self):
        self.driver = None
        self.json_path = os.path.join(PROJECT_ROOT, "data", "elements.json")  # 统一JSON路径

    def init_browser(self, desc_key, needed_url):
        """
        初始化浏览器并打开目标网页
        :param desc_key: JSON中"desc"字段的值（如"目标网页封装"）
        """
        self.driver = webdriver.Edge()
        self.driver.maximize_window()
        # 从JSON读取对应desc的url并访问
        url_data = get_json_element(self.json_path, desc_key, needed_url)
        self.driver.get(url_data.get(needed_url))

    def get_element_locator(self, desc_key, element_key):
        """
        从JSON获取元素定位表达式
        :param desc_key: JSON中"desc"字段的值（如"登陆页面元素封装"）
        :param element_key: 元素在JSON中的key（如"login_link"）
        :return: 元素定位表达式（字符串）
        """
        element_data = get_json_element(self.json_path, desc_key, [element_key])
        selector = element_data.get(element_key)
        if selector:
            return (By.CSS_SELECTOR, selector)